package com.config;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.token.JwtGenerator;
import org.springframework.security.oauth2.server.authorization.token.OAuth2RefreshTokenGenerator;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;

import java.security.*;

@Configuration
public class Oauth2TokenConfig {


    @Bean
    public JWKSource<SecurityContext> randomRsaJwkSource() throws NoSuchAlgorithmException {
        // 创建RSA密钥对生成器
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

        // 初始化密钥对生成器（指定密钥长度）
        keyPairGenerator.initialize(2048); // 以 2048 位长度初始化

        // 生成RSA密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // 将RSA密钥对转换为JWKSet对象
        JWKSet jwkSet = new JWKSet(
                new RSAKey.Builder((java.security.interfaces.RSAPublicKey) keyPair.getPublic())
                        .privateKey(keyPair.getPrivate())

                        .build());



        // 创建JWKSource对象
        JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(jwkSet);

        // 打印JWKSet对象的JSON表示
        System.out.println(jwkSet.toJSONObject().toString());

        return jwkSource;
    }

    @Bean
    public OAuth2TokenGenerator<Jwt> jwtTokenGenerator() throws NoSuchAlgorithmException {
        JwtEncoder jwtEncoder = new NimbusJwtEncoder(
                randomRsaJwkSource()
        );
        return new JwtGenerator(jwtEncoder);
    }

    @Bean
    public OAuth2RefreshTokenGenerator oAuth2RefreshTokenGenerator(){

        return new OAuth2RefreshTokenGenerator();
    }
}
